﻿using System.Collections.Generic;
using System.Text;

namespace Iorz.DomainSearch.Utils.Tools
{
    public class Cookies
    {
        private class CookieInfo
        {
            public string Name { get; set; }

            public string Value { get; set; }
        }

        private static string[] sCookieNames = new string[] { "Domain=", "Path=", "Expires=", "Max-age=", "Max-Age=" };

        private List<CookieInfo> mCookies = new List<CookieInfo>();

        public int Count
        {
            get { return mCookies.Count; }
        }

        public void Clear()
        {
            mCookies.Clear();
        }

        public void Update(string cookies)
        {
            if (string.IsNullOrEmpty(cookies) || !cookies.Contains("="))
                return;

            cookies = cookies.Replace("\r\n", string.Empty);
            var arrCookies = cookies.Split(';');

            var strTemp = string.Empty;
            var tempName = string.Empty;
            var tempValue = string.Empty;

            foreach (var item in arrCookies)
            {
                strTemp = item.Trim();
                foreach (var name in sCookieNames)
                {
                    if (strTemp.Contains(name) || strTemp.Contains(name.ToLower()) || strTemp.Contains(name.ToUpper()))
                        strTemp = strTemp.Substring(strTemp.IndexOf(name) + name.Length);
                }

                if (!strTemp.Contains("="))
                    continue;

                tempName = strTemp.Substring(0, strTemp.IndexOf("="));
                if (tempName.Contains(",")) tempName = tempName.Substring(tempName.LastIndexOf(",") + 1);

                tempValue = strTemp.Substring(strTemp.IndexOf("=") + 1);

                lock (this.mCookies)
                {
                    var cookie = mCookies.Find(c => c.Name == tempName);
                    if (cookie == null)
                    {
                        mCookies.Add(new CookieInfo()
                        {
                            Name = tempName,
                            Value = tempValue
                        });
                    }
                    else
                        cookie.Value = tempValue;
                }
            }
        }

        public string GetValue(string name)
        {
            var cookie = mCookies.Find(c => c.Name.Trim() == name.Trim());
            if (cookie == null)
                return null;

            return cookie.Value;
        }

        public override string ToString()
        {
            var str = new StringBuilder();
            foreach (var cookie in mCookies)
            {
                str.Append($"{cookie.Name}={cookie.Value};");
            }

            return str.ToString();
        }
    }
}
